#include "../Tools/ZLog.h"
#include <algorithm>
#include <iostream>
#include <ctime>
#include <iomanip>

GLOBAL_NAMESPACE_BEGIN

Log::Log(const std::string &name, const std::string& fileName, bool debugOutput)
    :   logLevel_(LOGLEVEL_NORMAL),
        bDebugOut_(debugOutput),
        logName_(name)
{
    log_.open(fileName);
}

Log::~Log()
{
    log_.close();
}

void Log::logMessage(const std::string& message, LogLevel level, bool bMaskDebug)
{
    if (bDebugOut_ && !bMaskDebug)
        std::cerr << message << std::endl;

    // write time into log
    struct tm *pTime;
    time_t ctTime;
    time(&ctTime);
    pTime = localtime(&ctTime);
    log_ << std::setw(2) << std::setfill('0') << pTime->tm_hour
        << ":" << std::setw(2) << std::setfill('0') << pTime->tm_min
        << ":" << std::setw(2) << std::setfill('0') << pTime->tm_sec
        << ": ";
    log_ << message << std::endl;
    log_.flush();
}

void Log::setDebugOutputEnabled(bool debugOutput)
{
    bDebugOut_ = debugOutput;
}

void Log::addListener(LogListener* listener)
{
    listeners_.push_back(listener);
}

void Log::removeListener(LogListener* listener)
{
    listeners_.erase(std::find(listeners_.begin(), listeners_.end(), listener));
}

Log::Stream Log::stream(LogLevel level, bool maskDebug)
{
    return Stream(this, level, maskDebug);
}

GLOBAL_NAMESPACE_END